package com.xzlcPT.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.util.MD5;
import com.util.MailUtilSSL;
import com.util.MakeKey;
import com.util.bean.EmailConf;
import com.util.bean.MessageInfo;
import com.xzlcPT.bean.XzCompany;
import com.xzlcPT.bean.XzLogin;
import com.xzlcPT.bean.XzMember;
import com.xzlcPT.service.LoginUserService;
import com.xzlcPT.service.RegisterService;
import com.xzlcPT.service.XzCompanyService;
import com.xzlcPT.service.XzMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * Controller 层 RegisterController
 *
 * @author 王天岳
 * @create 2017/3/30 17:43
 **/

@Controller
@RequestMapping("/XzRegister")
@SessionAttributes({"userLogin", "registerKey"})
public class RegisterController extends BaseController {
    @Autowired
    private RegisterService registerService;

    @Autowired
    private XzCompanyService companyService;

    @Autowired
    private LoginUserService loginUserService;

    @Autowired
    private XzMemberService memberService;

    //。。。。。。。。。。。。。。。。。。。。。。。。。。。移动端。。。。。。。。。。。。。。。。。。。。。。。。。。。

    //手机用户注册
    @ResponseBody
    @RequestMapping("selPhone.go")
    public Map selPhone(String phone, String password, String idcode) {
        Map map = new HashMap();
        map = ZCPhoneAll(phone, password, idcode);
        return map;
    }

    //短信发送
    private String send(String msgContent, String mobile, String template) throws Exception {
        String addr = "http://api.sms.cn/sms/";
        String userId = "aidan200";
        String pwd = "b7298cb8d99836a32c9c4ffe596bd142";
        String econd = "utf8";
        //组建请求
        String straddr = addr +
                "?ac=send&uid=" + userId +
                "&pwd=" + pwd +
                "&mobile=" + mobile +
                "&content=" + msgContent +
                "&econd=" + econd +
                "&template=" + template;
        StringBuffer sb = new StringBuffer(straddr);
        //System.out.println("URL:"+sb);
        //发送请求
        URL url = new URL(sb.toString());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        BufferedReader in = new BufferedReader(new InputStreamReader(
                url.openStream()));
        //返回结果
        String inputline = in.readLine();
        //System.out.println("Response:"+inputline);
        return inputline;
    }

    //短信注册验证码发送
    @ResponseBody
    @RequestMapping("addPhone.go")
    public Map addPhone(String phone, int type, HttpServletRequest request) throws IOException, MessagingException {
        Map map = new HashMap();
        map = SendPhoneAll(phone, type, request);
        return map;
    }

    //随机用户名
    public String count() {
        Date date = new Date();
        int max = 99999;
        int min = 9999;
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        Long d = date.getTime();
        String a = d.toString().substring(d.toString().length() - 6, d.toString().length());
        String count = "xz_" + a + "_" + s;
        return count;
    }

    //邮箱用户注册
    @ResponseBody
    @RequestMapping("selEmail.go")
    public Map selEmail(String email, String password, String idcode) {
        Map map = new HashMap();
        map = ZCEmailAll(email, password, idcode);
        return map;
    }

    //邮箱注册验证码发送
    @ResponseBody
    @RequestMapping("addEmail.go")
    public Map addEmail(String email, int type, HttpServletRequest request) throws IOException, MessagingException {
        Map map = new HashMap();
        map = SendEmailAll(email, type, request);
        return map;
    }

    //意见反馈
    @ResponseBody
    @RequestMapping("sendIdea.go")
    public Map sendIdea(String idea, HttpServletRequest request, @RequestHeader("accessToken") String token) throws IOException, MessagingException {
        Map map = new HashMap();
//        XzLogin xzLogin =loginUserService.selByToken(token);
        String toMail = "xianzhi_lc@sina.com";
        EmailConf ec = new EmailConf("sina");
        MessageInfo mi = new MessageInfo("findBack");
        List<String> toMails = new ArrayList<>();
        toMails.add(toMail);
        mi.setTo(toMails);
        String html = "<div style='width: 100%;" +
                "            min-width: 1100px;" +
                "            height: auto;" +
                "            overflow: hidden'>" +
                "    <div style='width: 600px;" +
                "            margin: 40px auto;" +
                "            height: 480px;" +
                "            border: 3px dashed #3d9ccc;" +
                "    padding: 40px'>" +
                "        <div style='padding: 20px;" +
                "            width: 90%;" +
                "            height: auto;" +
                "            margin: 0 auto'>" +
                "            <h3 style='color: #3d9ccc;margin-bottom: 30px'><b>" + idea + "</b></h3>" +
                "            <div style='font-size: 17px;" +
                "            margin-top: 10px'>" +
                "            <div style='font-size: 12px;" +
                "            margin-top: 30px;color: rgba(175,175,175,0.91)'>&emsp;&emsp;此邮件由先知网系统发出，系统不接收回信，请勿直接回复。</div>" +
                "        </div>" +
                "    </div>" +
                "</div>";
        mi.setMsg(html);
        //添加图片
        MimeBodyPart image = new MimeBodyPart();
        image.setDataHandler(new DataHandler(new FileDataSource(request.getSession().getServletContext().getRealPath("dist/foreEnd3/img/LOGO12.png"))));  //javamail jaf
        image.setContentID("g.png");
        //发送
        MailUtilSSL.sslSend(mi, ec, image);
        map.put("msg", "已发送");
        return map;
    }

    //邮箱验证码发送
    @ResponseBody
    @RequestMapping("/registerSendE.go")
    public Map registerSendE(String email, HttpServletRequest request, @RequestHeader("accessToken") String token) throws IOException, MessagingException {
        Map map = new HashMap();
        XzLogin xzLogin = loginUserService.selByToken(token);
        XzLogin login = registerService.selectEmail(email);
        if (xzLogin.getLoginId() != login.getLoginId()) {
            map.put("msg", "此邮箱已被注册!");
        } else {
            String key;
            Date time = new Date();
            String toMail = email;
            long sendTime = xzLogin.getLoginEmailTime().getTime();
            if (sendTime + 600000 < time.getTime()) {//超过十分钟
                key = MakeKey.makeKey();
                xzLogin.setLoginEmailKey(key);
                xzLogin.setFiled2(email);
                xzLogin.setLoginEmailTime(time);
                loginUserService.updateLoginEnd(xzLogin);
            } else {
                key = xzLogin.getLoginEmailKey();
            }
            EmailConf ec = new EmailConf("sina");
            MessageInfo mi = new MessageInfo("register");
            List<String> toMails = new ArrayList<>();
            toMails.add(toMail);
            mi.setTo(toMails);
            String html = "<div style='width: 100%;" +
                    "            min-width: 1100px;" +
                    "            height: auto;" +
                    "            overflow: hidden'>" +
                    "    <div style='width: 600px;" +
                    "            margin: 40px auto;" +
                    "            height: 480px;" +
                    "            border: 3px dashed #3d9ccc;" +
                    "    padding: 40px'>" +
                    "        <img src='cid:g.png' style='width: 150px;" +
                    "            height: 60px;" +
                    "            margin-left: 30px;" +
                    "            margin-top: 20px'>" +
                    "        <div style='padding: 20px;" +
                    "            width: 90%;" +
                    "            height: auto;" +
                    "            margin: 0 auto'>" +
                    "            <h3 style='color: #3d9ccc;margin-bottom: 30px'><b>先知网用户 您好</b></h3>" +
                    "            <div style='font-size: 17px;" +
                    "            margin-top: 10px'>" +
                    "                &emsp;&emsp;感谢您使用先知网，注册邮箱验证码为" +
                    "                <div style='color: #fc6866;font-size: 30px;text-align: center;margin-top: 10px'>" + key + "</div>" +
                    "            </div>" +
                    "            <div style='font-size: 12px;" +
                    "            margin-top: 30px;color: rgba(175,175,175,0.91)'>&emsp;&emsp;此邮件由先知网系统发出，系统不接收回信，请勿直接回复。</div>" +
                    "        </div>" +
                    "    </div>" +
                    "</div>";
            mi.setMsg(html);
            //添加图片
            MimeBodyPart image = new MimeBodyPart();
            image.setDataHandler(new DataHandler(new FileDataSource(request.getSession().getServletContext().getRealPath("dist/foreEnd3/img/LOGO12.png"))));  //javamail jaf
            image.setContentID("g.png");
            //发送
            MailUtilSSL.sslSend(mi, ec, image);
            map.put("msg", "已发送");
        }
        return map;
    }

    //邮箱验证码提交验证
    @ResponseBody
    @RequestMapping("registerSendE_YZ.go")
    public Map registerSendE_YZ(String email, String idcode, @RequestHeader("accessToken") String token) {
        Map map = new HashMap();
        XzLogin xzLogin = loginUserService.selByToken(token);
        if (email != null && idcode != null && xzLogin.getLoginEmailKey().equals(idcode) && xzLogin.getFiled2().equals(email)) {
            xzLogin.setLoginEmail(email);
            loginUserService.updateLoginEnd(xzLogin);
            map.put("msg", "ok");
        } else {
            map.put("msg", "邮箱或验证码错误");
        }
        return map;
    }

    //查询xzlogin
    @ResponseBody
    @RequestMapping("sel_XzLogin.go")
    public Map sel_XzLogin(@RequestHeader("accessToken") String token) {
        Map map = new HashMap();
        XzLogin xzLogin = loginUserService.selByToken(token);
        if (xzLogin.getLoginEmail() != null) {
            map.put("email", xzLogin.getLoginEmail());
            map.put("emailmsg", "err");
        } else {
            map.put("emailmsg", "ok");
        }
        map.put("phonemsg", xzLogin.getLoginPhone());
        return map;
    }

    //电话验证码发送
    @RequestMapping("/registerSendP.go")
    public Map registerSendP() {
        Map map = new HashMap();

        return map;
    }

    //邮箱验证码注册
    @RequestMapping("/registerSendER.go")
    public Map registerSendER() {
        Map map = new HashMap();

        return map;
    }

    //手机验证码注册
    @RequestMapping("/registerSendPR.go")
    public Map registerSendPR() {
        Map map = new HashMap();

        return map;
    }

    //。。。。。。。。。。。。。。。。。。。。。。。。。。。pc端。。。。。。。。。。。。。。。。。。。。。。。。。。。。
    //手机用户注册
    @ResponseBody
    @RequestMapping("selPhonePc.do")
    public Map selPhonePc(String phone, String password, String idcode) {
        Map map = new HashMap();
        map = ZCPhoneAll(phone, password, idcode);
        return map;
    }

    //短信注册验证码发送
    @ResponseBody
    @RequestMapping("addPhonePc.do")
    public Map addPhonePc(String phone, int type, HttpServletRequest request) throws IOException, MessagingException {
        Map map = new HashMap();
        map = SendPhoneAll(phone, type, request);
        return map;
    }

    //邮箱用户注册
    @ResponseBody
    @RequestMapping("selEmailPc.do")
    public Map selEmailPc(String email, String password, String idcode) {
        Map map = new HashMap();
        map = ZCEmailAll(email, password, idcode);
        return map;
    }

    //邮箱注册验证码发送
    @ResponseBody
    @RequestMapping("addEmailPc.do")
    public Map addEmailPc(String email, int type, HttpServletRequest request) throws IOException, MessagingException {
        Map map = new HashMap();
        map = SendEmailAll(email, type, request);
        return map;
    }

    //验证手机,验证码并注册
    private Map ZCPhoneAll(String phone, String password, String idcode) {
        Map map = new HashMap();
        XzLogin login = loginUserService.selByPhone(phone);
        XzLogin xzLogin = registerService.selectfiled1(phone);
        if (login == null) {
            if (phone != null && idcode != null && xzLogin.getLoginPhoneKey().equals(idcode) && xzLogin.getFiled1().equals(phone)) {
                xzLogin.setLoginPhone(phone);
                String strMd5 = MD5.md5(password);
                xzLogin.setLoginPassword(strMd5);
                xzLogin.setLoginActive(1);
                String count = count();
                System.out.println(count);
                xzLogin.setLoginCount(count);
                xzLogin.setFiled1("filed1");
                String t = MD5.md5(new Date().getTime() + count);
                xzLogin.setLoginToken(t);
                Map map1 = new HashMap();
                int loginmsg = 0;
                if (xzLogin.getLoginType() == 0) {
                    XzMember xzMember = new XzMember();
                    xzMember.setMemberName(count);
                    xzMember.setMemberEmail(xzLogin.getLoginEmail());
                    map1 = loginUserService.updateMember_ZC(xzLogin, xzMember);
                    loginmsg = Integer.parseInt(map1.get("lmsg").toString());
                    int menbermsg = Integer.parseInt(map1.get("mmsg").toString());
                    if (loginmsg == 0 || menbermsg == 0) {
                        map.put("msg", "注册失败");
                    }
                } else if (xzLogin.getLoginType() == 1) {
                    xzLogin.setFiled1("filed1");
                    loginmsg = loginUserService.updateLoginEnd(xzLogin);
                    if (loginmsg == 0) {
                        map.put("msg", "注册失败");
                    }
                }
                if (loginmsg > 0) map.put("token", t);
                map.put("userType", xzLogin.getLoginType());
                map.put("msg", "ok");
            } else {
                map.put("msg", "手机或验证码错误");
            }
        } else {
            map.put("msg", "此手机已被注册");
        }
        return map;
    }

    //注册时发送手机验证码
    private Map SendPhoneAll(String phone, int type, HttpServletRequest request) throws IOException, MessagingException {
        Map map = new HashMap();
        XzLogin login = loginUserService.selByPhone(phone);
        XzLogin xzLogin = registerService.selectfiled1(phone);
        try {
            String key = "";
            Date time = new Date();
            if (login != null) {
                map.put("msg", "此手机已被注册");
                return map;
            } else if (null != xzLogin) {//电话验证是否为空
                long sendTime = xzLogin.getLoginPhoneTime().getTime();
                if (sendTime + 600000 < time.getTime()) {//超过十分钟
                    key = MakeKey.getRandNum() + "";
                    xzLogin.setLoginPhoneKey(key);
                    xzLogin.setLoginPhoneTime(time);
                    loginUserService.updateByPrimaryKey(xzLogin);
                } else {
                    key = xzLogin.getLoginPhoneKey();
                }
            } else if (login == null && xzLogin == null) {
                XzLogin xzLogin1 = new XzLogin();
                key = MakeKey.getRandNum() + "";
                xzLogin1.setLoginPhoneKey(key);
                xzLogin1.setLoginPhoneTime(time);
                xzLogin1.setFiled1(phone);
                xzLogin1.setLoginActive(0);
                xzLogin1.setLoginType(type);
                if (type == 0) {
                    loginUserService.addUserForMember(xzLogin1);
                } else if (type == 1) {
                    loginUserService.addUserForCompany(xzLogin1);
                }
            }
            Map mapContent = new HashMap();
            mapContent.put("name", phone);
            mapContent.put("code", key);
            mapContent.put("time", "10");
            ObjectMapper mapper = new ObjectMapper();
            String content = mapper.writeValueAsString(mapContent);//map转json
            String msg = send(content, phone, "414143");
            Map maps = mapper.readValue(msg, Map.class);//发送返回值转map
            System.out.println(maps);
            map.put("msg", "已发送");
//            map.put("sendMsg", maps);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "err");
        }
        return map;
    }

    //验证邮箱,验证码并注册
    private Map ZCEmailAll(String email, String password, String idcode) {
        Map map = new HashMap();
        XzLogin login = registerService.selectEmail(email);
        XzLogin xzLogin = registerService.selectfiled2(email);
        String emailKye = xzLogin.getLoginEmailKey().toLowerCase();
        if (login == null) {
            if (xzLogin != null && emailKye != null) {
                if (email != null && idcode != null && emailKye.equals(idcode.toLowerCase()) && xzLogin.getFiled2().equals(email)) {
                    xzLogin.setLoginEmail(email);
                    String strMd5 = MD5.md5(password);
                    xzLogin.setLoginPassword(strMd5);
                    xzLogin.setLoginActive(1);
                    String count = count();
                    System.out.println(count);
                    xzLogin.setLoginCount(count);
                    xzLogin.setFiled2("filed2");
                    String t = MD5.md5(new Date().getTime() + count);
                    xzLogin.setLoginToken(t);
                    Map map1 = new HashMap();
                    int loginmsg = 0;
                    if (xzLogin.getLoginType() == 0) {
                        XzMember xzMember = new XzMember();
                        xzMember.setMemberName(count);
                        xzMember.setMemberEmail(xzLogin.getLoginEmail());
                        map1 = loginUserService.updateMember_ZC(xzLogin, xzMember);
                        loginmsg = Integer.parseInt(map1.get("lmsg").toString());
                        int menbermsg = Integer.parseInt(map1.get("mmsg").toString());
                        if (loginmsg == 0 || menbermsg == 0) {
                            map.put("msg", "注册失败");
                        }
                    } else if (xzLogin.getLoginType() == 1) {
                        xzLogin.setFiled2("filed2");
                        loginmsg = loginUserService.updateLoginEnd(xzLogin);
                        if (loginmsg == 0) {
                            map.put("msg", "注册失败");
                        }
                    }
                    if (loginmsg > 0) map.put("token", t);
                    map.put("userType", xzLogin.getLoginType());
                    map.put("msg", "ok");
                } else {
                    map.put("msg", "邮箱或验证码错误");
                }
            } else {
                map.put("msg", "邮箱或验证码错误");
            }
        } else {
            map.put("msg", "此邮箱已被注册");
        }
        return map;
    }

    //注册时发送邮箱验证码
    private Map SendEmailAll(String email, int type, HttpServletRequest request) throws IOException, MessagingException {
        Map map = new HashMap();
        XzLogin login = registerService.selectEmail(email);
        XzLogin xzLogin = registerService.selectfiled2(email);
        String key = "";
        Date time = new Date();
        String toMail = email;
        long sendTime;
        if (login != null) {
            map.put("msg", "此邮箱已被注册");
            return map;
        } else if (xzLogin != null) {
            sendTime = xzLogin.getLoginEmailTime().getTime();
            if (sendTime + 600000 < time.getTime()) {//超过十分钟
                key = MakeKey.makeKey();
                xzLogin.setLoginEmailKey(key);
                xzLogin.setFiled2(email);
                xzLogin.setLoginEmailTime(time);
                xzLogin.setLoginActive(0);
                xzLogin.setLoginType(type);
                loginUserService.updateLoginEnd(xzLogin);
            } else {
                key = xzLogin.getLoginEmailKey();
            }
        } else {
            XzLogin xzLogin1 = new XzLogin();
            key = MakeKey.makeKey();
            xzLogin1.setLoginEmailKey(key);
            xzLogin1.setFiled2(email);
            xzLogin1.setLoginEmailTime(time);
            xzLogin1.setLoginActive(0);
            xzLogin1.setLoginType(type);
            if (type == 0) {
                loginUserService.addUserForMember(xzLogin1);
            } else if (type == 1) {
                loginUserService.addUserForCompany(xzLogin1);
            }
        }
        EmailConf ec = new EmailConf("sina");
        MessageInfo mi = new MessageInfo("register");
        List<String> toMails = new ArrayList<>();
        toMails.add(toMail);
        mi.setTo(toMails);
        String html = "<div style='width: 100%;" +
                "            min-width: 1100px;" +
                "            height: auto;" +
                "            overflow: hidden'>" +
                "    <div style='width: 600px;" +
                "            margin: 40px auto;" +
                "            height: 480px;" +
                "            border: 3px dashed #3d9ccc;" +
                "    padding: 40px'>" +
                "        <img src='cid:g.png' style='width: 150px;" +
                "            height: 60px;" +
                "            margin-left: 30px;" +
                "            margin-top: 20px'>" +
                "        <div style='padding: 20px;" +
                "            width: 90%;" +
                "            height: auto;" +
                "            margin: 0 auto'>" +
                "            <h3 style='color: #3d9ccc;margin-bottom: 30px'><b>先知网用户 您好</b></h3>" +
                "            <div style='font-size: 17px;" +
                "            margin-top: 10px'>" +
                "                &emsp;&emsp;感谢您使用先知网，注册邮箱验证码为" +
                "                <div style='color: #fc6866;font-size: 30px;text-align: center;margin-top: 10px'>" + key + "</div>" +
                "            </div>" +
                "            <div style='font-size: 12px;" +
                "            margin-top: 30px;color: rgba(175,175,175,0.91)'>&emsp;&emsp;此邮件由先知网系统发出，系统不接收回信，请勿直接回复。</div>" +
                "        </div>" +
                "    </div>" +
                "</div>";
        mi.setMsg(html);
        //添加图片
        MimeBodyPart image = new MimeBodyPart();
        image.setDataHandler(new DataHandler(new FileDataSource(request.getSession().getServletContext().getRealPath("dist/foreEnd3/img/LOGO12.png"))));  //javamail jaf
        image.setContentID("g.png");
        //发送
        MailUtilSSL.sslSend(mi, ec, image);
        map.put("msg", "已发送");
        return map;
    }


    //    跳转到用户注册页面
    @RequestMapping("/goRegister.do")
    public ModelAndView toRegister() {
        ModelAndView mv = new ModelAndView("foreEnd3/registeru_1");
        XzLogin xzLogin = new XzLogin();
        xzLogin.setLoginType(0);
        mv.addObject("xzLogin", xzLogin);
        mv.addObject("state", 1);
        return mv;
    }

    //    跳转到企业注册页面
    @RequestMapping("/goRegisterC.do")
    public ModelAndView getRegister() {
        ModelAndView mv = new ModelAndView("foreEnd3/registerc_1");
        XzLogin xzLogin = new XzLogin();
        xzLogin.setLoginType(1);
        mv.addObject("xzLogin", xzLogin);
        return mv;
    }


    //    用户注册
    @RequestMapping("Register.do")
    public ModelAndView getRegisterMember(@Validated(XzLogin.Group.class) XzLogin xzLogin, BindingResult result, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("foreEnd3/registeru_1");
        if (xzLogin.getLoginType() == 1) {
            mv.setViewName("foreEnd3/registerc_1");
        }
        mv.addObject("xzLogin", xzLogin);
        mv.addObject("state", 1);
        if (!result.hasErrors()) {
            mv.addObject("state", 2);
            // 发送激活邮件
            try {
                sentEmail1(xzLogin, "/XzRegister/activeCount.do", "呵呵哒", request);
                //加密
                String strMd5 = MD5.md5(xzLogin.getLoginPassword());
                xzLogin.setLoginPassword(strMd5);
                xzLogin.setLoginActive(0);
                int rs = 0;
                if (xzLogin.getLoginType() == 0) {
                    rs = loginUserService.addUserForMember(xzLogin);
                } else if (xzLogin.getLoginType() == 1) {
                    rs = loginUserService.addUserForCompany(xzLogin);
                }
                if (rs != 0) {
                    mv.addObject("msg", "注册成功，请到邮箱中激活账号");
                } else {
                    mv.addObject("msg", "注册失败，请检查账号和邮箱");
                }
            } catch (Exception e) {
                e.printStackTrace();
                mv.addObject("msg", "发送失败,请检查邮箱");
            }
        }
        return mv;
    }

    //企业信息完善
    @RequestMapping("addCompanyByReg.do")
    public ModelAndView addCompanyByReg(Long companyId, String companyName, MultipartFile file, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("foreEnd3/registerc_1");
        mv.addObject("state", 4);
        mv.addObject("xzLogin", new XzLogin());
        if (file != null) {
            String fileName = (file.getOriginalFilename());
            System.out.println("开始");
            String path = request.getSession().getServletContext().getRealPath("uploadImg");
            String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
            fileName = new Date().getTime() + "." + prefix;
            System.out.println(path);
            File targetFile = new File(path, fileName);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            //保存
            try {
                file.transferTo(targetFile);
                XzCompany company = new XzCompany();
                company.setCompanyId(companyId);
                company.setCompanyName(companyName);
                company.setCompanyPicture(fileName);
                company.setCompanyState(1);
                int i = companyService.updateByPrimaryKeySelective(company);
                if (i == 1) {
                    mv.addObject("msg", "保存企业信息成功");
                } else {
                    mv.addObject("msg", "保存企业信息失败，请在企业信息中重新编辑");
                }
            } catch (Exception e) {
                e.printStackTrace();
                mv.addObject("msg", "营业执照上传失败，请在企业信息中重新上传");
            }
            return mv;
        }
        return mv;
    }


    //重新发送邮件
    @ResponseBody
    @RequestMapping("mailgoReplay.do")
    public Map mailgoReplay(Long loginId, String usertype, HttpServletRequest request) {
        System.out.println(loginId);
        Map map = new HashMap();
        map.put("usertype", usertype);
        map.put("loginId", loginId);
        XzLogin login = loginUserService.selLoginForMOrCById(map);
        map = new HashMap();
        if (login != null) {
            try {
                sentEmail1(login, "/XzRegister/activeCount.do", "呵呵哒", request);
                map.put("msg", "邮件发送成功，请到邮箱中激活账号");
            } catch (Exception e) {
                e.printStackTrace();
                map.put("msg", "邮件发送成功，请检查邮箱");
            }
        } else {
            map.put("msg", "不存在的用户，请重新注册");
        }
        return map;
    }


    //    激活账号
    @RequestMapping("activeCount.do")
    public ModelAndView activeCount(String username, String newTime) {
        ModelAndView mv = new ModelAndView("foreEnd3/registeru_1");
        mv.addObject("state", 3);
        XzLogin activeUser = selActiveUser(username);
        if (activeUser != null) {
            mv.addObject("xzLogin", activeUser);
            if (activeUser.getLoginType() == 1) {
                mv.setViewName("foreEnd3/registerc_1");
            }
            long activeTime = System.currentTimeMillis() - Long.parseLong(newTime);
            System.out.println(activeTime);
            if (activeTime < 86400000) {
                if (activeUser.getLoginActive() != 1) {
                    activeUser.setLoginActive(1);
                    System.out.println("激活测试:" + activeUser.getLoginCount());
                    int a = registerService.updateActiveCount(activeUser);
                    if (a != 1) {
                        mv.addObject("msg", "激活失败");
                    } else {
                        mv.addObject("msg", "激活成功");
                        //把登录成功后的用户加入session
                        Map map = new HashMap();
                        map.put("usertype", activeUser.getLoginType());
                        map.put("loginId", activeUser.getLoginId());
                        mv.addObject("userLogin", loginUserService.selLoginForMOrCById(map));
                    }
                } else {
                    if (activeUser.getLoginType() == 1) {
                        mv.addObject("state", 4);
                    }
                    mv.addObject("msg", "已经激活无需重复激活");
                }

            } else {
                mv.addObject("state", 2);
                mv.addObject("msg", "邮件已超过24小时,请重新发送邮件");
            }
        } else {
            mv.addObject("msg", "激活路径有误请重新登陆激活");
        }
        return mv;
    }



    //    判定用户名是否重复
    @ResponseBody
    @RequestMapping("selByUser.do")
    public Map<String, Object> selByUser(String str) {
        System.out.println(str);
        XzLogin loginU = new XzLogin(); //接收前台传入值
        loginU.setLoginCount(str);
        Map<String, Object> map = new HashMap<>();
        XzLogin newUser = new XzLogin();
        newUser = registerService.selectByUser(loginU);
        if (newUser == null) {
            map.put("selUser", "√");
            map.put("spanColor", "true");
        } else {
            map.put("selUser", "ｘ 用户名已存在");
            map.put("spanColor", "false");
        }
        return map;
    }

    // 查询邮箱是否存在
    @ResponseBody
    @RequestMapping("selByEmail.do")
    public Map<String, Object> selByEmail(String email) {
        Map<String, Object> map = new HashMap<>();
        XzLogin login = registerService.selectEmail(email);
        if (login != null) {
            map.put("msg", "ok");
        } else {
            map.put("msg", "err");
        }
        return map;
    }

    // 查询手机是否存在
    @ResponseBody
    @RequestMapping("selByPhone.do")
    public Map selByPhone(String phone) {
        Map<String, String> map = new HashMap<>();
        XzLogin login = registerService.selectPhone(phone);
        if (login != null) {
            map.put("msg", "ok");
        } else {
            map.put("msg", "err");
        }
        return map;
    }

    //    判定公司名是否重复
    @ResponseBody
    @RequestMapping("selByCompanyName.do")
    public Map<String, Object> selByCompanyName(String str) {
        Map<String, Object> map = new HashMap<>();
        XzCompany newCompanyInfo = new XzCompany();
        if (str != null && str != "") {
            System.out.println("公司名:" + str);
            /*newCompanyInfo = companyService.selectByCompany(str);
            if (newCompanyInfo != null) {
                System.out.println(newCompanyInfo.getCompanyName());
            }
            if (newCompanyInfo == null) {
                map.put("selCompany", "√");
                map.put("spanColor", "true");
            } else {
                map.put("selCompany", "ｘ 公司名已存在");
                map.put("spanColor", "false");
            }*/
        }
        return map;
    }

    //密码找回1 发送邮件
    @ResponseBody
    @RequestMapping("findBack1.do")
    public Map findBack1(String email, HttpServletRequest request) {
        Map map = new HashMap();
        try {
            sentEmail2(email, "/view/foreEnd3/retrievepassword.html", request);
            map.put("msg", "ok");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "err");
        }
        return map;
    }

    //密码找回1 发送短信
    @ResponseBody
    @RequestMapping("/findBackPhone1.do")
    public Map findBackPhone1(String phone) {
        Map<String, Object> map = new HashMap<>();
        XzLogin xzLogin = loginUserService.selByPhone(phone);
        String code = MakeKey.getRandNum() + "";
        xzLogin.setLoginPhoneKey(code);
        loginUserService.updateByPrimaryKey(xzLogin);
        Map<String, Object> mapContent = new HashMap<>();
        mapContent.put("name", phone);
        mapContent.put("code", code);
        mapContent.put("time", "10");
        ObjectMapper mapper = new ObjectMapper();
        try {
            String content = mapper.writeValueAsString(mapContent);//map转json
            String msg = send(content, phone, "414143");
            Map maps = mapper.readValue(msg, Map.class);//发送返回值转map
            System.out.println(maps);
            map.put("msg", "ok");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "err");
        }
        return map;
    }

    //密码找回2 验证 验证码
    @ResponseBody
    @RequestMapping("findBack2.do")
    public Map findBack2(String email, String key) {
        Map map = new HashMap();
        XzLogin login = registerService.selectEmail(email);
        if (key != null && key.equals(login.getLoginEmailKey())) {
            map.put("msg", "ok");
        } else {
            map.put("msg", "err");
        }
        return map;
    }

    //密码找回2 验证手机验证码
    @ResponseBody
    @RequestMapping("findBackPhone2.do")
    public Map findBackPhone2(String phone, String key) {
        Map map = new HashMap();
        XzLogin login = registerService.selectPhone(phone);
        if (key != null && key.equals(login.getLoginPhoneKey())) {
            map.put("msg", "ok");
        } else {
            map.put("msg", "err");
        }
        return map;
    }

    //密码找回3 修改密码
    @ResponseBody
    @RequestMapping("findBack3.do")
    public Map findBack3(String password, String email, String key) {
        Map map = new HashMap();
        XzLogin login = registerService.selectEmail(email);
        if (key != null && key.equals(login.getLoginEmailKey())) {
            login.setLoginEmailKey(null);
            String strMd5 = MD5.md5(password);
            login.setLoginPassword(strMd5);
            int i = loginUserService.updateByPrimaryKey(login);
            if (i > 0) {
                map.put("msg", "ok");
            } else {
                map.put("msg", "err");
            }
        } else {
            map.put("msg", "miss");
        }
        return map;
    }

    //密码找回3 修改密码 手机
    @ResponseBody
    @RequestMapping("findBackPhone3.do")
    public Map findBackPhone3(String password, String phone, String key) {
        Map map = new HashMap();
        XzLogin login = registerService.selectPhone(phone);
        if (key != null && key.equals(login.getLoginPhoneKey())) {
            login.setLoginPhoneKey(null);
            String strMd5 = MD5.md5(password);
            login.setLoginPassword(strMd5);
            int i = loginUserService.updateByPrimaryKey(login);
            if (i > 0) {
                map.put("msg", "ok");
            } else {
                map.put("msg", "err");
            }
        } else {
            map.put("msg", "miss");
        }
        return map;
    }

    //发送密码找回
    private void sentEmail2(String email, String callBack, HttpServletRequest request) throws IOException, MessagingException {
        String args = "?type=2&email=" + email;
        String toMail = email;
        XzLogin login = registerService.selectEmail(email);
        String key = MakeKey.makeKey();
        login.setLoginEmailKey(key);
        loginUserService.updateByPrimaryKey(login);
        String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        EmailConf ec = new EmailConf("sina");
        MessageInfo mi = new MessageInfo("findBack");
        List<String> toMails = new ArrayList<>();
        toMails.add(toMail);
        mi.setTo(toMails);
        String html = "<div style='width: 100%;" +
                "            min-width: 1100px;" +
                "            height: auto;" +
                "            overflow: hidden'>" +
                "    <div style='width: 600px;" +
                "            margin: 40px auto;" +
                "            height: 480px;" +
                "            border: 3px dashed #3d9ccc;" +
                "    padding: 40px'>" +
                "        <img src='cid:g.png' style='width: 150px;" +
                "            height: 60px;" +
                "            margin-left: 30px;" +
                "            margin-top: 20px'>" +
                "        <div style='padding: 20px;" +
                "            width: 90%;" +
                "            height: auto;" +
                "            margin: 0 auto'>" +
                "            <h3 style='color: #3d9ccc;margin-bottom: 30px'><b>先知网用户 您好</b></h3>" +
                "            <div style='font-size: 17px;" +
                "            margin-top: 10px'>" +
                "                &emsp;&emsp;感谢您使用先知网，修改密码的验证码为" +
                "                <div style='color: #fc6866;font-size: 30px;text-align: center;margin-top: 10px'>" + key + "</div>" +
                "            </div>" +
                "            <a style='width: 120px;" +
                "            height: 40px;" +
                "            margin-top: 30px;" +
                "            background-color: #FFA500;" +
                "            border: none;" +
                "            color: #FFFFff;" +
                "            outline: none;" +
                "            border-radius: 3px;" +
                "            display: block;" +
                "            font-size: 15px;" +
                "text-align: center;line-height: 40px;margin-left: 150px" +
                "' href='" + path + callBack + args + "'>密码找回</a>" +
                "            <div style='font-size: 12px;" +
                "            margin-top: 30px;color: rgba(175,175,175,0.91)'>&emsp;&emsp;点击按钮进行密码找回，此邮件由先知网系统发出，系统不接收回信，请勿直接回复。</div>" +
                "        </div>" +
                "    </div>" +
                "</div>";
        mi.setMsg(html);
        //添加图片
        MimeBodyPart image = new MimeBodyPart();
        image.setDataHandler(new DataHandler(new FileDataSource(request.getSession().getServletContext().getRealPath("dist/foreEnd3/img/LOGO12.png"))));  //javamail jaf
        image.setContentID("g.png");
        //发送
        MailUtilSSL.sslSend(mi, ec, image);
    }

    //    发送注册邮件方法
    private void sentEmail1(XzLogin xzLogin, String callBack, String information, HttpServletRequest request) throws IOException, MessagingException {
        System.out.println("发邮件:" + xzLogin.getLoginEmail());
        long newTime = System.currentTimeMillis();
        String args = "?username=" + xzLogin.getLoginCount() + "&newTime=" + newTime;
        String user = xzLogin.getLoginCount();
        String toMail = xzLogin.getLoginEmail();
        String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        EmailConf ec = new EmailConf("sina");
        MessageInfo mi = new MessageInfo("register");
        List<String> toMails = new ArrayList<>();
        toMails.add(toMail);
        mi.setTo(toMails);
        String html = "<div style='width: 100%;" +
                "            min-width: 1100px;" +
                "            height: auto;" +
                "            overflow: hidden'>" +
                "    <div style='width: 600px;" +
                "            margin: 40px auto;" +
                "            height: 680px;" +
                "            border: 3px dashed #3d9ccc;" +
                "    padding: 40px'>" +
                "        <img src='cid:g.png' style='width: 150px;" +
                "            height: 60px;" +
                "            margin-left: 30px;" +
                "            margin-top: 30px'>" +
                "        <div style='padding: 20px;" +
                "            width: 90%;" +
                "            height: auto;" +
                "            margin: 0 auto'>" +
                "            <h3 style='color: #fc6866;margin-bottom: 30px'><b>亲爱的" + user + " ,您好</b></h3>" +
                "            <div style='font-size: 17px;" +
                "            margin-top: 10px'>" +
                "                &emsp;&emsp;欢迎您成为先知网注册用户，为了您能随时接收与您匹配的高薪职位推荐，邀请您完成 邮箱验证。" +
                "            </div>" +
                "            <div style='font-size: 17px;" +
                "            margin-top: 10px'>" +
                "                &emsp;&emsp;同时，为了您能够快速收到企业HR和猎头顾问的精准职位邀请，让简历曝光机会提升68%，成功应聘率提升23%，我们强烈建议您完善简历。" +
                "            </div>" +
                "" +
                "            <a style='width: 230px;" +
                "            height: 40px;" +
                "            margin-top: 30px;" +
                "            background-color: #FFA500;" +
                "            border: none;" +
                "            color: #FFFFff;" +
                "            outline: none;" +
                "            border-radius: 3px;" +
                "            display: block;" +
                "            font-size: 15px;" +
                "text-align: center;line-height: 40px' href='" + path + callBack + args + "'>开启邮箱验证，走进先知世界</a>" +
                "            <img src='cid:e.png' style='width: 200px;height: 130px;margin-top: 30px;float: right'>" +
                "        </div>" +
                "    </div>" +
                "</div>";
        mi.setMsg(html);
        //添加图片
        MimeBodyPart image = new MimeBodyPart();
        image.setDataHandler(new DataHandler(new FileDataSource(request.getSession().getServletContext().getRealPath("dist/foreEnd3/img/LOGO12.png"))));  //javamail jaf
        image.setContentID("g.png");
        MimeBodyPart image2 = new MimeBodyPart();
        image2.setDataHandler(new DataHandler(new FileDataSource(request.getSession().getServletContext().getRealPath("dist/foreEnd3/img/celebrate.png"))));  //javamail jaf
        image2.setContentID("e.png");
        //发送
        MailUtilSSL.sslSend(mi, ec, image, image2);
    }

    //    根据用户名查询
    public XzLogin selActiveUser(String str) {
        XzLogin loginU = new XzLogin(); //接收前台传入值
        loginU.setLoginCount(str);
        XzLogin newUser = registerService.selectByUser(loginU);
        return newUser;
    }


    //    跳转到修改密码页面
    @RequestMapping("goForget.do")
    public ModelAndView goGetPW() {
        ModelAndView mv = new ModelAndView("foreEnd/forgetPassword");
        return mv;
    }


    //    密码找回(发送邮件)
    @RequestMapping("getPassword.do")
    public ModelAndView getPassword(String username, String email, HttpServletRequest request) {
        System.out.println(username + "     " + email);
        ModelAndView mv = new ModelAndView("foreEnd/jump");
        XzLogin getUser = new XzLogin();
        XzLogin newUser = new XzLogin();
        if (username != null && !"".equals(username) && email != null && !"".equals(email)) {
            getUser.setLoginCount(username);
            getUser.setLoginEmail(email);
            newUser = registerService.getPassword(getUser);
        }
        if (newUser != null) {
            String sEmail = "/XzRegister/goUpdatePW.do";
            //sentEmail(newUser, sEmail, "找回吧", request);
            mv.addObject("jumpInfo", "邮件已发送!");

        } else {
            mv.addObject("jumpInfo", "该用户不存在!");
            System.out.println("未查到该用户!");
        }
//        添加跳转地址
        mv.addObject("jumpAddress", "goIndex.do");
        return mv;
    }

    //    跳转到修改密码页面
    @RequestMapping("goUpdatePW.do")
    public ModelAndView updatePW(String username, String newTime, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("foreEnd/updatePassword");
        XzLogin newUser = new XzLogin();
        newUser = registerService.selectByCount(username);
        long activeTime = System.currentTimeMillis() - Long.parseLong(newTime);
        if (username != null && !"".equals(username)) {
            if (activeTime < 1800000) {
                mv.addObject("updCount", newUser);
            } else {
                mv = new ModelAndView("foreEnd/jump");
                String sEmail = "/XzRegister/goUpdatePW.do";
                String info = "邮件已超过24小时,请重新填写!";
                mv.addObject("jumpInfo", info);
                mv.addObject("jumpAddress", "goIndex.do");
                //sentEmail(newUser, sEmail, info, request);
                System.out.println("邮件已超过24小时!");
            }
        }
        return mv;
    }

    //    修改密码
    @RequestMapping("UpdatePassword.do")
    public ModelAndView updatePassword(String newCount, String password, String confirmPassword) {
        ModelAndView mv = new ModelAndView("foreEnd/jump");
        System.out.println(newCount + "          " + password);
        boolean b1 = password.equals(confirmPassword);
        if (newCount != null && newCount != "" && password != null && password != "") {
            if (b1) {
                XzLogin xzLogin = new XzLogin();
                xzLogin.setLoginCount(newCount);
                xzLogin.setLoginPassword(MD5.md5(password));
                System.out.println("MD5:" + xzLogin.getLoginPassword());
                registerService.updatePassword(xzLogin);
                mv.addObject("jumpInfo", "新密码设置成功!");
                mv.addObject("jumpAddress", "goIndex.do");
            } else {
                mv.setViewName("foreEnd/updatePassword");
                XzLogin newUser = registerService.selectByCount(newCount);
                mv.addObject("password", password);
                mv.addObject("confirmPassword", confirmPassword);
                mv.addObject("confirmPasswordSpan", "两次密码不一致");
                mv.addObject("updCount", newUser);
            }
        } else {
            mv.addObject("jumpInfo", "新密码设置失败!");
            mv.addObject("jumpAddress", "goIndex.do");
        }
        return mv;
    }
}
